package com.wtwd.device.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zdl
 * @Description
 * @create 2021-07-27 9:55
 */
public class SignUtil {
    public static String md5(String text) {
        try {
            //1、生成一个MD5加密计算摘要
            MessageDigest instance = MessageDigest.getInstance("MD5");
            //2 、将消息变成byte数组
            byte[] bytes = text.getBytes();
            //3 、计算MD5加密后的16字节（128位）摘要
            byte[] buff = instance.digest(bytes);
            //4 把字节数组转换成16进制字符串
           return bytesToHex(buff);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuffer md5str = new StringBuffer();
        //把数组每一字节换成16进制连成md5字符串
        int digital;
        for (int i = 0; i < bytes.length; i++) {
            digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toUpperCase();
    }


}
